const cloud = require('wx-server-sdk')
const request = require('request')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})

async function getWechatPosts(accessToken, offset, count) {
  let url = `https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=${accessToken}`
  //let url = `https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=${accessToken}`
  var options = {
    method: 'POST',
    json: true,
    uri: url,
    body: {
      "type": "news",
      "offset": offset,
      "count": count
    }
  }
  const rp = options =>
    new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) {
          reject(error);
        }
        resolve(response);
      });
    });
  const result = await rp(options)
  let rbody = (typeof result === 'object') ? result : JSON.parse(result);
  let item = result.body.item
  console.log(item[0].content.news_item[0])
  let lists = []

  for(let j=0;j<item.length;j++){
    let list = {}
    let news_item = item[j].content.news_item;
    for(let k=0;k<news_item.length;k++){
      list.title=news_item[k].title;//标题
      list.url=encodeURIComponent(news_item[k].url);//链接
      list.image_url=news_item[k].thumb_url;//封面
      list.digest=news_item[k].digest;//摘要
      list.author=news_item[k].author;//作者   
      if(list.author.indexOf('摄影学院') != -1){
        list.author=list.author.replace('摄影学院','')
        lists.push(list)
      }  
    }
   

  }






  return lists;
}

// 云函数入口函数
exports.main = async (event, context) => {
  let token = null;
  await cloud.callFunction({
    name: 'getAccessToken'
  }).then(function (data) {
    token = data.result;
  });

  let offset = event.offset||0;
  let count = event.count||10;
  let res = getWechatPosts(token,offset,count);
  



  return res;
}